<template>
  <div>
    <el-dialog title="新增角色" :visible="dialogVisible" @close="onClose">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="启用">
          <div class="custom-switch">
            <el-switch
              v-model="ruleForm.state"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
            <span class="text">{{ Boolean(ruleForm.state) ? '已启用' :'未启用' }}</span>
          </div>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="ruleForm.description" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">确认</el-button>
          <el-button @click="onClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { postSysRole } from '@/api/role/role'
export default {
  name: 'RoleDialog',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      value: true,
      ruleForm: {
        name: '',
        description: '',
        state: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    onClose() {
      this.$refs.ruleFormRef.validateField()
      this.$emit('update:dialogVisible', false)
      this.$emit('update-list')
      this.$refs.ruleFormRef.resetFields()
    },
    async submit() {
      try {
        await this.addRole()
        this.$message.success('角色新增成功')
        this.onClose()
      } catch (error) {
        this.onClose()
        console.log(error)
      }
    },
    // 角色新增
    async addRole() {
      await postSysRole(this.ruleForm)
    }
  }
}
</script>

<style lang='scss' scoped>
.custom-switch {
  display: flex;
  align-items: center;
  .text {
    margin-left: 5px;
  }
}
</style>
